package xyz.jangle.thread.test.n2_7.stampedlock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;

/**
 * StampedLock的Demo
 * @author Administrator
 *
 */
public class M2 {
	
	private static Integer a =0;

	public static void main(String[] args) {
		
		StampedLock lock = new StampedLock();
		
		// 写线程
		new Thread(() -> {
			for(int i=0;i<3;i++) {
				System.out.println("开始获取写锁");
				long stamp = lock.writeLock();
				try {
					System.out.println("获取到写锁，进行写操作");
					a++;
					try {
						TimeUnit.SECONDS.sleep(2);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}finally {
					lock.unlockWrite(stamp);
				}
				try {
					System.out.println("无锁等待3秒");
					TimeUnit.SECONDS.sleep(3);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();
		
		// 读线程
		new Thread(() ->{
			for(int i=0;i<20;i++) {
				System.out.println("开始获取乐观读锁");
				long stamp = lock.tryOptimisticRead();
				int retVal = a;
				// 检查在读取过程中是否有写操作
				if(!lock.validate(stamp)) {
					// 如果写锁已获取，则升级为悲观锁
					System.out.println("写锁已获取，升级为悲观读锁");
					stamp = lock.readLock();
					try {
						retVal = a;
					}finally {
						lock.unlockRead(stamp);
					}
				}
				System.out.println("读取到a数值："+retVal);
				try {
					TimeUnit.MILLISECONDS.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}).start();

	}
	
	

}
